package com.cby.android.sample.model

import android.app.Application
import com.cby.android.library.base.BaseStateViewModel
import com.cby.android.sample.bean.wan.WanBannerBean
import com.cby.android.sample.intent.HomeIntent
import com.cby.android.sample.repository.CaiYunApiImpl
import com.cby.android.sample.repository.WanAndroidApiImpl
import com.cby.android.sample.state.HomeState

class HomeViewModel(application: Application) : BaseStateViewModel<HomeState, HomeIntent>(application) {


    private val wanAndroidApi = WanAndroidApiImpl()

    private val caiYunApi = CaiYunApiImpl()

    private var currentPage: Int = 0

    private fun loadData(location: String) {
        fetchDataWithNoStatus {
            if(currentPage > 0){
                val articleResponse = wanAndroidApi.getArticles(currentPage)
                updateState(HomeState(
                    wanArticles = articleResponse.data.datas, page = currentPage
                ))
            }else{
                showLoading()
                val weatherResponse = caiYunApi.getWeatherFromCaiyun(location)
                val bannerResponse = wanAndroidApi.getBanners()
                val articleResponse = wanAndroidApi.getArticles(currentPage)
                updateState(HomeState(
                    wanArticles = articleResponse.data.datas,
                    wanBanners = bannerResponse.data as MutableList<WanBannerBean>,
                    dataCaiYunWeather = weatherResponse.result.realtime,
                    page = currentPage
                ))
                showContent()
            }
        }
    }


    override fun showError(errorMsg: String?) {
        if(currentPage > 0){
            updateState(HomeState(
                errorMsg = errorMsg
            ))
        }else{
            super.showError(errorMsg)
        }

    }




    override fun dispatch(intent: HomeIntent) {
        when(intent) {
            is HomeIntent.LoadDataIntent -> {
                currentPage = 0
                loadData(intent.location)
            }
            HomeIntent.LoadMoreDataIntent -> {
                currentPage++
                loadData("")
            }
        }
    }

}